#!/usr/bin/env python3
# -*- coding: utf-8 -*-

from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from app.core.config import settings

# 根据配置创建数据库连接URL
if hasattr(settings, 'MYSQL_HOST'):
    # 使用MySQL配置
    DATABASE_URL = f"mysql+pymysql://{settings.MYSQL_USER}:{settings.MYSQL_PASSWORD}@{settings.MYSQL_HOST}:{settings.MYSQL_PORT}/{settings.MYSQL_DATABASE}"
else:
    # 使用默认的SQLite配置
    DATABASE_URL = "sqlite:///./functional_test.db"

# 创建数据库引擎
engine = create_engine(
    DATABASE_URL,
    pool_pre_ping=True,
    echo=settings.is_development  # 开发环境下显示SQL语句
)

# 创建会话工厂
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)

def get_db():
    """获取数据库会话"""
    db = SessionLocal()
    try:
        yield db
    finally:
        db.close()

def create_tables():
    """创建数据库表"""
    from app.models.test_models import Base
    Base.metadata.create_all(bind=engine)
    print("✅ 功能测试平台数据库表创建完成")

def init_database():
    """初始化数据库"""
    try:
        create_tables()
        return True
    except Exception as e:
        print(f"❌ 数据库初始化失败: {str(e)}")
        return False 